package Day1.ZuoYe;

import Kit.DBUtil;

import java.sql.*;
import java.util.Scanner;

//2 insert操作支持返回主键，写个例子。
public class InsertTest {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "insert into s_subject(subjectname,classhour,gradeid) values(?,?,?)";
        try {
            con = DBUtil.getConnection();
            System.out.println("请输入课程名字：");
            String sbname = input.next();
            System.out.println("请输入课程时长：");
            int hour = input.nextInt();
            System.out.println("请输入年纪编号：");
            int gradeid = input.nextInt();
            ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            ps.setString(1,sbname);
            ps.setInt(2,hour);
            ps.setInt(3,gradeid);
            int i = ps.executeUpdate();
            System.out.println(i>0?"添加成功！":"添加失败！");
            rs  = ps.getGeneratedKeys();
            if(rs .next())
                System.out.println("主键是："+rs.getObject(1));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally{
            DBUtil.close(rs );
            DBUtil.close(ps);
            DBUtil.close(con);
        }
    }
}
